import * as echarts from '../../ec-canvas/echarts';
import {
  Admin
} from '../../apis/index'

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    showBtns: {
      type: Boolean,
      value: false
    },
    type: {
      type: String,
      value: 'cloth'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    index: 0,
    ec: {
      lazyLoad: true,
      isLoaded: false,
      isDisposed: false
      // onInit: initChart
    },
    dataList: {
      actlPerHour: 0,
      goalPerHour: 0,
      todayCompleteRate: 0,
      todayDiff: 0,
      outputs: []
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    change(e) {
      console.log(e.currentTarget.dataset.index);
      this.setData({
        index: e.currentTarget.dataset.index
      });
    },
    // 点击按钮后初始化图表
    init: function () {
      this.ecComponent.init((canvas, width, height, dpr) => {
        // 获取组件的 canvas、width、height 后的回调函数
        // 在这里初始化图表
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        setOption(chart, this.data.dataList);

        // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
        this.chart = chart;

        this.setData({
          isLoaded: true,
          isDisposed: false
        });

        // 注意这里一定要返回 chart 实例，否则会影响事件处理等
        return chart;
      });
    },

    dispose: function () {
      if (this.chart) {
        this.chart.dispose();
      }

      this.setData({
        isDisposed: true
      });
    }
  },
  lifetimes: {
    attached() {
      this.ecComponent = this.selectComponent('#mychart-dom-bar')
      getCompleteRate.call(this)
    }
  }
})

/**
 * @Description 设置表单项
 * @author 孙畅
 * @date 2020-11-06
 * @param {any} chart
 * @param {Array} dataList
 * @returns {any}
 */
function setOption(chart, dataList) {
  var option = {
    color: ['#3398DB'],
    tooltip: {
      trigger: 'axis',
      axisPointer: { // 坐标轴指示器，坐标轴触发有效
        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [{
      type: 'category',
      data: dataList.outputs.map(item => item.time),
      axisTick: {
        alignWithLabel: true
      }
    }],
    yAxis: [{
      type: 'value'
    }],
    series: [{
      name: '直接访问',
      type: 'bar',
      barWidth: '60%',
      data: dataList.outputs.map(item => item.output)
    }]
  };
  chart.setOption(option);
}
/**
 * @Description 获取完成率数据
 * @author 孙畅
 * @date 2020-11-03
 * @returns {any}
 */
function getCompleteRate() {
  Admin.getCompleteRate().then(res => {
    console.log('获取完成比例', res)
    this.data.dataList = res.data.data[this.data.type]
    this.setData({
      dataList: this.data.dataList
    })
    this.init()
  })
}